<template>
  <div class="user-profile">
    <el-dialog
      v-model="dialogVisible"
      title="个人信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="profile-form"
      >
        <!-- 基本信息 -->
        <div class="section-title">基本信息</div>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" disabled />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="居住地" prop="location">
          <el-input v-model="form.location" placeholder="请输入居住地" />
        </el-form-item>

        <el-form-item label="头像">
          <div class="avatar-upload">
            <el-avatar :size="60" :src="form.avatar" class="current-avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <el-button type="primary" size="small">更换头像</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 密码修改 -->
        <div class="section-title">密码修改</div>
        
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="form.currentPassword"
            type="password"
            show-password
            placeholder="请输入当前密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            show-password
            placeholder="请确认新密码"
          />
        </el-form-item>

        <!-- 状态信息 -->
        <div class="section-title">账户状态</div>
        
        <el-form-item label="状态">
          <el-tag :type="form.status === 'active' ? 'success' : 'danger'">
            {{ form.status === 'active' ? '正常' : '禁用' }}
          </el-tag>
        </el-form-item>

        <el-form-item label="注册时间">
          <span class="register-time">{{ formatDate(form.registerTime) }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="loading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'

const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  username: '',
  phone: '',
  email: '',
  location: '',
  avatar: '',
  status: 'active',
  registerTime: '',
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 打开对话框
const open = (userData) => {
  Object.assign(form, userData)
  // 清空密码字段
  form.currentPassword = ''
  form.newPassword = ''
  form.confirmPassword = ''
  dialogVisible.value = true
}

// 确认密码验证
function validateConfirmPassword(rule, value, callback) {
  if (value !== form.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }

  // 模拟上传成功
  const reader = new FileReader()
  reader.onload = (e) => {
    form.avatar = e.target.result
  }
  reader.readAsDataURL(file)
  
  return false // 手动处理上传
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 保存信息
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 如果有密码修改
    if (form.currentPassword && form.newPassword) {
      // 这里应该调用API修改密码
      ElMessage.success('密码修改成功')
    }

    ElMessage.success('个人信息更新成功')
    dialogVisible.value = false
  } catch (error) {
    console.error('保存失败', error)
  } finally {
    loading.value = false
  }
}

// 暴露方法供外部调用
defineExpose({
  open
})
</script>

<style scoped>
.user-profile {
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #409EFF;
    margin: 20px 0 15px 0;
    padding-bottom: 8px;
    border-bottom: 1px solid #e4e7ed;
  }

  .profile-form {
    max-height: 60vh;
    overflow-y: auto;
    padding-right: 10px;
  }

  .avatar-upload {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .current-avatar {
    border: 1px dashed #dcdfe6;
  }

  .register-time {
    color: #909399;
    font-size: 14px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}

/* 滚动条样式 */
.profile-form::-webkit-scrollbar {
  width: 6px;
}

.profile-form::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.profile-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.profile-form::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>